package com.earogya.logic.medical_records;

import java.util.Calendar;

import org.apache.struts.ehr.medical_records.model.Query;

import com.earogya.Constants;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.message.QRY_A19;

/**
 * Creates QRY A19 message to query information about the admissions
 * of a given patient.
 * @author Chamendri
 *
 */
public class CreateQRYA19 {

	private QRY_A19 qry;
	private Query query;
	
	/**
	 * Accepts Query object.
	 * @param query
	 */
	public CreateQRYA19(Query query){
		this.qry=new QRY_A19();
		this.query=query;
	}
	
	/**
	 * Creates HL7 QRY A19 message.
	 * @param sendingFacility
	 * @return
	 * @throws HL7Exception
	 */
	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addRequiredInformation();
		return qry.getMessage().encode();
	}
	
	/**
	 * Add MSH segment to HL7 QRY A19 message.
	 * @param sendingFacility
	 * @throws DataTypeException
	 */
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		qry.getMSH().getFieldSeparator().setValue("|");
		qry.getMSH().getEncodingCharacters().setValue("^~\\&");
		qry.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		qry.getMSH().getMessageType().getMsg1_MessageCode().setValue("QRY");
		qry.getMSH().getMessageType().getTriggerEvent().setValue("A19");
		qry.getMSH().getSendingApplication().getUniversalID().setValue(Constants.SENDING_APPLICATION);
		qry.getMSH().getVersionID().getVersionID().setValue(Constants.HL7_VERSION);
		qry.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		qry.getMSH().getReceivingApplication().getUniversalID().setValue(Constants.RECEIVING_APPLICATION_PATIENT_VISIT_SERVICE);
		qry.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}
	
	/**
	 * Add QRD segment to QRY A19 message.
	 * @throws DataTypeException
	 */
	private void addRequiredInformation() throws DataTypeException{
		qry.getQRD().getWhoSubjectFilter(0).getIDNumber().setValue(query.getPatientId());
		qry.getQRD().getWhatSubjectFilter(0).getText().setValue(query.getSearch_type());
	}
	
}
